#include "loadmusic.h"

loadmusic::loadmusic(QString title,QObject *parent) : QObject(parent),m_title(title)
{
    m_client=nullptr;
    m_file=nullptr;
    state=MusicLoadState::Noload;
}



//这里是一个bug打撒撒旦撒旦的撒的

/// @brief /dasdad的撒大
void loadmusic::run()d
{
     state=MusicLoadState::loading;
     std::thread*pa=new std::thread(receivenetwork,this,m_title);
     std::thread*pa1=new std::thread(GatherNetWork,this,m_title);
     pa->join();
     pa1->join();
     emit destory(this);
}

loadmusic::~loadmusic()
{
    if(m_client!=nullptr)
    {
        delete m_client;
    }
    if(m_file!=nullptr)
    {
        m_file->close();
        delete  m_file;                ;
    }
}

void loadmusic::receivenetwork(loadmusic *lm, QString title)
{
    //打开文件
    QString filepath("song/");
    filepath.append(title).append(".mp3");
    lm->m_file=new QFile(filepath);
    if (!lm->m_file->open(QIODevice::WriteOnly))
    {
        qDebug() << "Failed to open file for writing: " << lm->m_file->errorString();
        return;
    }
    while(lm->state==MusicLoadState::loading)
    {

        {
             unique_lock<mutex>l(lm->m_mtx);
             while(lm->m_data.empty() && lm->state==MusicLoadState::loading)
             {
                 lm->m_NoNull.wait(l);
             }

        }
        if(lm->m_data.empty() || lm->state!=MusicLoadState::loading)
        {

            return ;
        }
        lm->m_mtx.lock();
        lm->m_file->write(lm->m_data.front());
        lm->m_data.pop();
        lm->m_mtx.unlock();
    }


}

void loadmusic::GatherNetWork(loadmusic *lm, QString title)
{

    lm->m_client=new tcpclient();
    QString str;
     str.append("usrnameid:{1373474316}\\r\\npassword:{137347}\\r\\nPlaySong:{")
             .append(title).append("}\\r\\n");
     lm->m_client->write(str);
     lm->m_client->send();
    while(lm->state==MusicLoadState::loading)   //下载中
    {
        // 检查连接状态
        if (lm->m_client->m_socket->state() == QAbstractSocket::UnconnectedState) {
            // 连接已关闭，跳出while循环
            emit lm->play(title);
            break;
        }
        if(!lm->m_client->m_socket->waitForReadyRead())
        {
            continue;
        }
        lm->m_mtx.lock();
        QByteArray arr=lm->m_client->m_socket->readAll();
        lm->m_data.push(arr);
        lm->m_mtx.unlock();
        lm->m_NoNull.notify_one();
    }
    while(!lm->m_data.empty()){  //等待另外一个线程结束
    }
    lm->m_NoNull.notify_one();      //杀死线程
    lm->m_mtx.lock();
    lm->state=MusicLoadState::endload;  //下载结束
    lm->m_mtx.unlock();

}


